<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Merchant;
use App\Services\MerchantService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class MerchantsController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:user');
    }

    public function index(Request $request)
    {
        $builder = Merchant::query();
        $builder->where('user_id', $request->user('user')->id);

        $merchants = $builder->paginate();
        return view('user.merchants.index', compact('merchants'));
    }

    public function edit(Merchant $merchant)
    {

        return view('user.merchants.edit', compact('merchant'));
    }

    public function update(Merchant $merchant, Request $request)
    {
        $validator = Validator::make($request->all(), [
            'notify_type' => ['required', 'in:' . implode(',', array_keys(Merchant::$notifyTypeMap))]
        ], [
            'notify_type.required' => '请选择支付类型',
            'notify_type.in'       => '支付类型错误'
        ]);
        $validator->validate();

        $merchant->notify_type = $request->input('notify_type');
        $merchant->save();
        return redirect()->route('user.merchants.index')->with('success', '修改成功');
    }

    public function cash(Merchant $merchant, Request $request)
    {
        $user = $request->user('user');

        $cashInfo = $user->cashInfo;
        if (is_null($cashInfo)) {
            return redirect()->route('user.cashinfos.index')->with('error', '请完成提现信息');
        }

        $info = $user->cashInfo;
        return view('user.merchants.cash', compact('merchant', 'user', 'info'));
    }

    public function cashDraw(Merchant $merchant, Request $request, MerchantService $merchantService)
    {
        $amount = $merchant->balance - $merchant->frozen_balance;

        $request->validate([
            'amount' => [
                'required',
                function ($attribute, $value, $fail) use($amount) {
                    if ($value <= 0) {
                        $fail('提现金额错误');
                    }
                    if ($value > $amount) {
                        $fail('最大可提现金额' . $amount);
                    }
                }
            ],
            'remark' => ['max:200']
        ], [
            'amount.required' => '提现金额不能为空',
            'remark.max' => '最大长度为200'
        ]);

        $data = $request->only(['amount', 'remark']);

        $merchantService->cashDraw($request->user(), $merchant, $data['amount'], $request->user()->username, $data['remark'] ?? '');
        return redirect()->route('user.merchants.index')->with('success', '提现请求成功a');
    }
}
